package operation_log

import (
	"context"
	"github.com/pkg/errors"
	"github.com/xinliangnote/go-gin-api/configs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewModel() *OperationLog {
	return new(OperationLog)
}

func (p *OperationLog) Create(db *mongo.Client) (err error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("operation_log")
	_, err = client.InsertOne(context.TODO(), p)
	return err
}

func (p *OperationLog) List(db *mongo.Client, pageIndex uint, pageSize uint) (list []OperationLog, err error) {
	var productList []OperationLog

	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("operation_log")
	skip := int64((pageIndex - 1) * pageSize)
	findOptions := options.Find()
	findOptions.SetSort(bson.D{{"_id", -1}})
	findOptions.SetSkip(skip)
	findOptions.SetLimit(int64(pageSize))

	find, err := client.Find(context.TODO(), bson.M{}, findOptions)
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return nil, err
	}

	err = find.All(context.TODO(), &productList)
	if err != nil {
		return nil, err
	}

	return productList, nil
}

func (p *OperationLog) Count(db *mongo.Client) (count int64, err error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("operation_log")
	count, err = client.CountDocuments(context.TODO(), bson.D{})
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return 0, err
	}
	return count, nil
}
